package com.zhouz.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zhouz.activiti.entity.vo.ActivitiModel;
import com.zhouz.activiti.service.ActivitiService;
import com.zhouz.common.base.entity.dto.Result;
import lombok.extern.log4j.Log4j2;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.http.HttpStatus;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-06 13:34
 */
@RestController
@Log4j2
@RequestMapping("/activiti")
public class ActivitiAuthorityController implements ModelDataJsonConstants {

    @Resource
    protected RepositoryService repositoryService;
    @Resource
    protected ObjectMapper objectMapper;

    @Resource
    private ActivitiService activitiService;

    /**
     * 新增流程模型
     * @return
     */
    @GetMapping(value = "/addModeler")
    @ResponseBody
    public Result<String> addModel(ActivitiModel model) {
        log.info("addModel paramter:" + JSON.toJSONString(model));
        if(model == null){
            model = new ActivitiModel();
            model.setName("请假流程");
            model.setKey("demo1");
            model.setCategory("1");
            model.setDesc("请假流程");
        }
        Result<String> data = null;
        try {
            String modelId = activitiService.addModel(model);
            data = Result.success(modelId);
        } catch (Exception e) {
            log.error("addModel error：", e);
            data = Result.fail(1, "创建模型失败");
        }
        log.info("addModel end !");
        return data;
    }

    @RequestMapping("/editModel")
    public ObjectNode getEditorJson(String modelId) {
        ObjectNode modelNode = null;
        Model model = repositoryService.getModel("2501");
        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = objectMapper.createObjectNode();
                    modelNode.put(MODEL_NAME, model.getName());
                }
                modelNode.put(MODEL_ID, model.getId());
                ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
                        new String(repositoryService.getModelEditorSource(model.getId()), "utf-8"));
                modelNode.put("model", editorJsonNode);
            } catch (Exception e) {
                log.error("Error creating model JSON", e);
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        return modelNode;
    }

    @RequestMapping(value = "/model/save", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void saveModel(@RequestParam String modelId, @RequestBody MultiValueMap<String, String> values) {
        log.info("saveModel invoke ,paramter[modelId:" + modelId + ";values:" + JSON.toJSONString(values));
        List<String> list = values.get("json_xml");
        String json = list.get(0);
        Map<String, Object> map = new GsonJsonParser().parseMap(json);
        log.info("模型定义保存成功！");
    }

    @RequestMapping(value = "/editor/stencilset")
    public String getStencilset() {
        InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
        try {
            return IOUtils.toString(stencilsetStream, "utf-8");
        } catch (Exception e) {
            throw new ActivitiException("Error while loading stencil set", e);
        }
    }


}